from app import db
from datetime import datetime

class Product(db.Model):
    __tablename__ = 'product'

    product_id = db.Column(db.String(36), primary_key=True, comment='商品ID')
    product_name = db.Column(db.String(100), nullable=False, comment='商品名称')
    category_id = db.Column(db.String(36), nullable=False, comment='分类ID')
    shop_id = db.Column(db.String(36), nullable=False, comment='店铺ID')
    product_desc = db.Column(db.Text, comment='商品描述')
    price = db.Column(db.Numeric(10, 2), nullable=False, comment='商品价格')
    original_price = db.Column(db.Numeric(10, 2), comment='原价')
    cover_img = db.Column(db.String(200), comment='封面图片')
    product_type = db.Column(db.String(1), default='1', comment='商品类型（1课程 2电子书 3音频）')
    status = db.Column(db.String(1), default='0', comment='商品状态（0上架 1下架）')
    sales = db.Column(db.Integer, default=0, comment='销量')
    create_time = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    update_time = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')

    # 1对多关联CourseResource
    course_resources = db.relationship('CourseResource', backref='product', lazy='dynamic')
    def to_dict(self):
        return {
            'productId': self.product_id,
            'productName': self.product_name,
            'categoryId': self.category_id,
            'shopId': self.shop_id,
            'productDesc': self.product_desc,
            'price': float(self.price) if self.price else None,
            'originalPrice': float(self.original_price) if self.original_price else None,
            'coverImg': self.cover_img,
            'productType': self.product_type,
            'status': self.status,
            'sales': self.sales,
            'createTime': self.create_time.strftime('%Y-%m-%d %H:%M:%S') if self.create_time else None,
            'updateTime': self.update_time.strftime('%Y-%m-%d %H:%M:%S') if self.update_time else None,
            'courseResources': [resource.to_dict() for resource in self.course_resources]
        }